package org.wedding.center.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.wedding.center.dto.query.AttachQuery;
import org.wedding.center.dto.query.ProductQuery;
import org.wedding.center.dto.vo.AttachVo;
import org.wedding.center.entity.AttachInfo;
import org.wedding.center.entity.ProductCategory;
import org.wedding.center.entity.ProductInfo;
import org.wedding.center.mapper.AttachInfoMapper;
import org.wedding.center.mapper.ProductInfoMapper;
import org.wedding.center.service.AttachInfoService;
import org.wedding.center.service.ProductCategoryService;
import org.wedding.center.service.ProductInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.wedding.enums.system.ResultCodeEnum;
import org.wedding.system.entity.UserInfo;
import org.wedding.system.mapper.UserMapper;
import org.wedding.utils.CommonResult;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import org.wedding.dto.PageModel;
import org.wedding.utils.PageUtil;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品信息表(ProductInfo)表服务实现类
 *
 * @author songkaiyue
 * @since 2025-05-19 17:26:19
 */
@Service
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper, ProductInfo> implements ProductInfoService {
    @Resource
    private ProductCategoryService productCategoryService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AttachInfoMapper attachInfoMapper;

    /**
     * 分页查询所有数据
     *
     * @return
     */
    @Override
    public CommonResult<PageModel> findAll(ProductQuery query) {
        try {
            List<ProductInfo> list = baseMapper.selectAll(query);
            List<ProductInfo> setList = query.setList(PageUtil.getListPage(query.getCurrent(), query.getPageSize(), list), list.size());
            for (ProductInfo productInfo : setList) {
                if (StrUtil.isNotEmpty(productInfo.getUserId())) {
                    UserInfo userInfo = userMapper.findById(productInfo.getUserId());
                    if (ObjectUtil.isNotEmpty(userInfo)) {
                        productInfo.setMerchantPhone(userInfo.getContactPhone());
                    }
                }
            }
            query.setList(setList, list.size());
            return CommonResult.success(query);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }

    }

    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult<ProductInfo> view(String id) {
        try {
            ProductInfo productInfo = baseMapper.findById(id);
            List<AttachVo> attachVos = new ArrayList<>();
            List<AttachInfo> attachInfos = attachInfoMapper.selectAll(AttachQuery.builder().businessId(id).build());
            if (!attachInfos.isEmpty()) {
                for (AttachInfo attachInfo : attachInfos) {
                    attachVos.add(AttachVo.builder()
                            .id(attachInfo.getId())
                            .name(attachInfo.getAttachName())
                            .url(attachInfo.getFilePath())
                            .status("success")
                            .build());
                }
            }
            productInfo.setAttachInfos(attachVos);
            if (StrUtil.isNotEmpty(productInfo.getUserId())){
                UserInfo userInfo = userMapper.findById(productInfo.getUserId());
                productInfo.setMerchantPhone(userInfo.getContactPhone());
            }
            return CommonResult.success(productInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 新增数据
     *
     * @param productInfo
     * @return
     */
    @Override
    public CommonResult add(ProductInfo productInfo) {
        try {
            productInfo.setId(IdUtil.simpleUUID());
            productInfo.setCreateTime(DateUtil.now());
            productInfo.setDelFlag("0");
            String userId = StpUtil.getSession().get("userId").toString();
            productInfo.setUserId(userId);
            setColum(productInfo);
            baseMapper.insert(productInfo);
            return CommonResult.success(productInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    public void setColum(ProductInfo productInfo) {
        if (StrUtil.isNotEmpty(productInfo.getCategoryId())) {
            ProductCategory category = productCategoryService.getById(productInfo.getCategoryId());
            if (ObjectUtil.isNotEmpty(category)) {
                productInfo.setCategoryName(category.getCategory());
            }
        }
        if (ObjectUtil.isNotEmpty(productInfo.getAttachIds()) && !productInfo.getAttachIds().isEmpty()) {
            productInfo.getAttachIds().forEach(attachId -> {
                AttachInfo attach = attachInfoMapper.selectById(attachId);
                if (ObjectUtil.isNotEmpty(attach)) {
                    attach.setBusinessId(productInfo.getId());
                    attach.setUpdateTime(DateUtil.now());
                    attachInfoMapper.updateById(attach);
                }
            });
        }
    }

    /**
     * 修改数据
     *
     * @param productInfo
     * @return
     */
    @Override
    public CommonResult updateEntity(ProductInfo productInfo) {
        try {
            setColum(productInfo);

            baseMapper.updateById(productInfo);
            return CommonResult.success(productInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 删除数据
     *
     * @param ids
     * @return
     */
    @Override
    public CommonResult delete(List<String> ids) {
        try {
            if (ObjectUtil.isEmpty(ids)) return CommonResult.failed(ResultCodeEnum.PARAM_ERROR);
            for (String id : ids) {
                baseMapper.upDeleteById(id);
            }
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

}
